# -*- coding:utf8 -*-
"""
游戏配置的全局变量 - ConfigEnvSet
"""
import utils.json_utils as json
from framework.core.context import action_context_storage
from utils.traceback_utils import print_exc
from framework.firefly_dc.singleton import Singleton


class GameConfigEnv(object):
    """游戏配置的全局变量所对应的程序实体"""
    __metaclass__ = Singleton

    def __init__(self):
        from framework.dal.gameconfig.query import getProfileList
        envList = getProfileList('ConfigEnvSet')

        for env in envList:
            value = env.EnvValue
            vType = env.ValueType
            try:
                if vType == 'int':
                    value = int(value)
                elif vType == 'float':
                    value = float(value)
                elif vType == 'json':
                    value = json.loads(value)
                setattr(self, env.EnvKey, value)
            except ValueError as ve:
                ve.message = 'Load GemeEnv({})[{}] = {} Failed!'.format(env, vType, value)
                print_exc(ve)

    def reload_data(self):
        """重载全局配置"""
        raise NotImplementedError
        # from common.dbToRedisManager import profileManager
        # profileManager.update_profile('ConfigEnvSet')
        # self.__init__()


class GameConfigEnvLang(object):
    """
    游戏配置的全局变量所对应的程序实体

    多语言支持
    """
    __metaclass__ = Singleton

    def __init__(self):
        from framework.dal.gameconfig.query import getProfileList
        from framework.bll.lang.translate import translate_config_to_dict
        env_list = getProfileList('ConfigEnvSetLang')

        for env in env_list:
            try:
                value = translate_config_to_dict(env)
                setattr(self, env.EnvKey, value)

            except ValueError as e:
                e.message = 'Load GemeEnvLang({}) = {} Failed!'.format(env, value)
                print_exc(e)

    def reload_data(self):
        """重载全局配置"""
        raise NotImplementedError
        # from common.dbToRedisManager import profileManager
        # profileManager.update_profile('ConfigEnvSet')
        # self.__init__()


def get_config_env_set(key, trans=False, code=None):
    """
    获取 ConfigEnvSet 中的配置值。

    :param bool trans: 是否多语言
    :param str code: 语言代码
    """

    # 如果有语言代码则取对应文本
    if trans or code:
        if code:
            language_code = code

        # 根据语言上下文获取对应的值
        else:
            language_code = str(action_context_storage.ctx.lang)

        value = getattr(GameConfigEnvLang(), key)
        trans_value = value.get(language_code)
        return trans_value

    else:
        return getattr(GameConfigEnv(), key)


def get_config_by_lang(env_cfg_key):
    """获取多语言全局配置"""
    from framework.core.context import action_context_storage
    from utils.lang_utils import LanguageUtils
    max_len_dict = get_config_env_set(env_cfg_key)
    try:
        lang_code = action_context_storage.ctx.lang
        max_len = max_len_dict[lang_code]
    except KeyError:
        from common.service_config import get_app_id
        lang_code = LanguageUtils.get_default_lang(app_id=get_app_id())
        max_len = max_len_dict[lang_code]
    except Exception:
        return False, None

    return True, max_len


if __name__ == "__main__":
    print GameConfigEnv().ActivityAchieveMaxPhase
